<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ajax extends Home_Controller{
	public function __construct(){
		parent::__construct();
		$this->load->database();
	}

	public function sendMail($subject, $message){
		$this->load->library('email');
		$config['protocol'] = "smtp";
		$config['smtp_host'] = "ssl://smtp.gmail.com";
		$config['smtp_port'] = "465";
		$config['smtp_user'] = "khoinguyen.net.vn@gmail.com"; 
		$config['smtp_pass'] = "60@111.79";
		$config['charset'] = "utf-8";
		$config['mailtype'] = "html";
		$config['newline'] = "\r\n";
		
		$this->email->initialize($config);

		$this->email->from('khoinguyen.net.vn@gmail.com', 'Administrator');
		$this->email->to('info@khoidesign.net');
		
		$this->email->subject($subject);
		$this->email->message($message);
		
		$this->email->send();
	}

	public function order_by_link(){
		if (!$this->input->is_ajax_request()) {
		   exit('No direct script access allowed');
		}else{
			$name = $this->input->post('fullnameLink');
	    	$email = $this->input->post('emailLink');
	    	$phone = $this->input->post('phoneLink');
	    	$content = $this->input->post('contentLink');
			$link = $this->input->post('link');

			$dataInsert = array(
				'fullname' => $name,
				'email' => $email,
				'phone' => $phone,
				'content' => $content,
				'link' => $link,
				'date_create' => date("Y-m-d"),
			);
			$this->db->insert('tpt_order', $dataInsert);
			$subject = 'Khách hàng gửi file bằng link';
			$message = 'Khách hàng: '.$name.' có email: '.$email.', số điện thoại là: '.$phone.' đã gửi file bằng link: '.$link.' và có nội dung là: '.$content;	
			$this->sendMail($subject, $message);
			
			$respone['statusCheck'] = 1;
			echo json_encode($respone);
		}
	}
	
	public function upload_file(){
		if (!$this->input->is_ajax_request()) {
		   exit('No direct script access allowed');
		}else{
			$name = $this->input->post('fullname');
	    	$email = $this->input->post('email');
	    	$phone = $this->input->post('phone');
	    	$content = $this->input->post('content');
			$content = htmlentities($content, ENT_QUOTES);
			if($_FILES){
				$ftp_server = '116.118.112.25';
				$ftp_user_name = 'Khoi_G';
				$ftp_user_pass = '123456';
				// set up basic connection
				$conn_id = ftp_connect($ftp_server);
				// login with username and password
				$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
	
				// Check open
				if ((!$conn_id) || (!$login_result)) {
			        $respone['statusCheck'] = 0;
			    } else {
					$nameUrl = nv_EncString($name).'_'.time();
	
		    		if(!is_dir('ftp://' . $ftp_user_name . ':' . $ftp_user_pass . '@' . $ftp_server . '/khoiNguyenCompany/upload')){
						@ftp_mkdir($conn_id, 'khoiNguyenCompany/upload');
					}
					if(!is_dir('ftp://' . $ftp_user_name . ':' . $ftp_user_pass . '@' . $ftp_server . '/khoiNguyenCompany/upload/' . date("Y"))){
						@ftp_mkdir($conn_id, 'khoiNguyenCompany/upload/' . date("Y"));
					}
					if(!is_dir('ftp://' . $ftp_user_name . ':' . $ftp_user_pass . '@' . $ftp_server . '/khoiNguyenCompany/upload/' . date("Y") . '/' . date("m"))){
						@ftp_mkdir($conn_id, 'khoiNguyenCompany/upload/' . date("Y") . '/' . date("m"));
					}
					if(!is_dir('ftp://' . $ftp_user_name . ':' . $ftp_user_pass . '@' . $ftp_server . '/khoiNguyenCompany/upload/' . date("Y") . '/' . date("m") . '/' . date("d"))){
						@ftp_mkdir($conn_id, 'khoiNguyenCompany/upload/' . date("Y") . '/' . date("m") . '/' . date("d"));
					}
	
					if(!is_dir('ftp://' . $ftp_user_name . ':' . $ftp_user_pass . '@' . $ftp_server . '/khoiNguyenCompany/upload/' . date("Y") . '/' . date("m") . '/' . date("d") .'/'. $nameUrl)){
						@ftp_mkdir($conn_id, 'khoiNguyenCompany/upload/' . date("Y") . '/' . date("m") . '/' . date("d") .'/'. $nameUrl);
					}
					$foder	=	date("Y")."/".date("m")."/".date("d")."/".$nameUrl."/";
					$file_ary = $this->reArrayFiles($_FILES['file']);
					$dataFilesUpload = array();
					foreach ($file_ary as $file) {
						$source_file = $file['tmp_name'];
						$dest_file = 'khoiNguyenCompany/upload/'.$foder.'/'.$file['name'];
						$ret = ftp_nb_put($conn_id, $dest_file, $source_file, FTP_BINARY, FTP_AUTORESUME);
						while (FTP_MOREDATA == $ret)
						{
							$ret = ftp_nb_continue($conn_id);
						}
					}
					$dataInsert = array(
						'fullname' => $name,
						'email' => $email,
						'phone' => $phone,
						'content' => $content,
						'folder_name' => $nameUrl,
						'date_create' => date("Y-m-d"),
					);
					$this->db->insert('tpt_order', $dataInsert);
					
					$subject = 'Khách hàng gửi file bằng ftp';
					$message = 'Khách hàng: '.$name.' có email: '.$email.', số điện thoại là: '.$phone.' đã gửi file bằng ftp tới folder: '.$nameUrl.' và có nội dung là: '.$content;
					$this->sendMail($subject, $message);

					$respone['statusCheck'] = 1;				
				}
			}else{
				$respone['statusCheck'] = 0;
			}
			echo json_encode($respone);
		}
	}

	public function reArrayFiles(&$file_post) {

	    $file_ary = array();
	    $file_count = count($file_post['name']);
	    $file_keys = array_keys($file_post);

	    for ($i=0; $i<$file_count; $i++) {
	        foreach ($file_keys as $key) {
	            $file_ary[$i][$key] = $file_post[$key][$i];
	        }
	    }

	    return $file_ary;
	}

	public function chat(){
		// $ipAddress = $this->input->ip_address();
		$ipAddress = $this->input->post('ipAddress');
	    $pathChat = APPPATH.'../assets/chat/';
	    $fileChat = $ipAddress.'.txt';
	    $fullPath = $pathChat.$fileChat;
	    if(!file_exists($fullPath)) {
	    	$content = '';
			$fp = fopen($fullPath,"wb");
			fwrite($fp,$content);
			fclose($fp);
	    }
		$time = date('Y-m-d H:i:s');
		//$nickname = 'Guest';
		$message = $this->input->post('message');
		//$nickname = htmlentities(strip_tags($nickname));
		$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
		$message = htmlentities(strip_tags($message));
		if($message != "\n"){
			if(preg_match($reg_exUrl, $message, $url)) {
				$message = preg_replace($reg_exUrl, '<a href="'.$url[0].'" target="_blank">'.$url[0].'</a>', $message);
			}
			// $content = "<span>". $nickname . "</span>" . $message = str_replace("\n", " ", $message) . "\n";
			$message = str_replace("\n", " ", $message);
			// $content = '<li class="right clearfix"><span class="chat-img pull-right"><img src="'.base_url()."public/templates/home/images/guest.gif".'" alt="Guest Avatar" class="img-circle" /></span><div class="chat-body clearfix"><div class="header"><small class=" text-muted"><span class="glyphicon glyphicon-time"></span>'.$time.'</small><strong class="pull-right primary-font">'.$nickname.'</strong></div><p>'.$message.'</p></div></li>'. "\n";
			$content = '2|'.$time.'|'.$message.'|1'. "\n";
			$fp = fopen($fullPath, 'a');
			fwrite($fp,$content);
			fclose($fp);
		}
	}

	public function showChat(){
		$ip = $this->input->ip_address();
		$pathChat = APPPATH.'../assets/chat/';
		$response = array();
		$fileChat = $ip.'.txt';
		$fullPath = $pathChat.$fileChat;
		if(file_exists($fullPath)){
			$lines = file($fullPath);
		}
		$text= array();
		foreach ($lines as $line_num => $line){
			if($line_num >= $state){
				$text[] =  $line = str_replace("\n", "", $line);
			}
		}
		$response['text'] = $text; 
		echo json_encode($response);
	}

	public function changeGallery(){
		if (!$this->input->is_ajax_request()) {
		   exit('No direct script access allowed');
		}else{
			$id = $this->input->post('id');
	        $this->db->where('gallery_id',$id);
	        $dataImages = $this->db->get('tpt_gallery_images')->result_array();

		    $html = '<div class="col-md-12" id="carousel-bounding-box">
		      	<div id="myCarousel" class="carousel slide">
		        	<div class="carousel-inner">';
			        	$i=0;
			        	foreach ($dataImages as $value) {
			            	if($i == 0){
			              		$html .= '<div class="item active" data-slide-number="'.$i.'">';
			                	$html .= '<img src="'.base_url().$value['images'].'" class="img-responsive" width="1200" height="480">';
			              		$html .= '</div>';
			            	}else{
			              		$html .= '<div class="item" data-slide-number="'.$i.'">';
			                	$html .= '<img src="'.base_url().$value['images'].'" class="img-responsive" width="1200" height="480">';
			              		$html .= '</div>';
			            	}
			            	$i++;
			          	}
		        $html .= '</div>
		        <a class="left carousel-control" href="#myCarousel" data-slide="prev">
		          <span class="glyphicon glyphicon-chevron-left"></span>
		        </a>
		        <a class="right carousel-control" href="#myCarousel" data-slide="next">
		          <span class="glyphicon glyphicon-chevron-right"></span>
		        </a>
		        <ol class="carousel-indicators">';
		          	$i=0;
		          	foreach ($dataImages as $value) {
		            	if($i == 0){
		              		$html .= '<li data-target="#myCarousel" data-slide-to="'.$i.'" class="active"></li>';
		            	}else{
		              		$html .= '<li data-target="#myCarousel" data-slide-to="'.$i.'"></li>';
		            	}
		           	 	$i++;
		          	}
		        $html .= '</ol>
		      </div>
		    </div>
		    <div id="slider-thumbs">';
		        $i=0;
		        foreach ($dataImages as $value) {
		          	$html .= '<div class="col-xs-6 col-md-3 col-sm-4">
			            <div class="dummy"></div>
			            <div class="in">
			              	<a href="#" class="thumbnail" id="carousel-selector-'.$i.'">
			                	<img src="'.base_url().$value['thump'].'" alt="" class="img-responsive">
			              	</a>
			            </div>
		          	</div>';
		          	$i++;
		        }
		    $html .= '</div>';
		    $respone['html'] = $html;
		    echo json_encode($respone);
		}
	}
}